#include "Connection.h"

#include <cppconn/connection.h>
#include <cppconn/driver.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

#include <cstdio>
#include <memory>

Connection::Connection(const std::string& ip, unsigned short port,
                       const std::string& user, const std::string& password,
                       const std::string& dbname) {
    sql::Driver* driver = get_driver_instance();  // no need to delete

    char host[1024] = {0};
    sprintf(host, "tcp://%s:%d", ip.c_str(), port);

    _conn = driver->connect(host, user, password);
    _conn->setSchema(dbname);

    _stmt = _conn->createStatement();
}

bool Connection::update(std::string sql) {
    return _stmt->executeUpdate(sql);
}

std::shared_ptr<sql::ResultSet> Connection::query(std::string sql) {
    return std::shared_ptr<sql::ResultSet>(
        _stmt->executeQuery(sql));  // rvalue optimization
}
